package inventory

import (
	"errors"
	"regexp"
	"strings"
)

// 导入跳板机
// gosh inventory import --type bastion --method file --path xxxx.txt
// gosh inventory import --type host --method api --path xxxx.yaml

// gosh inventory get --type bastion
// gosh inventory get --type host --label vendor=tencent --label region=shanghai --label project=ops

// gosh inventory delete --type host --label vendor=tencent --label private_ip=xxxx
// gosh inventory delete --type bastion xxx

var ImportConfig = &Import{}
var FilterConfig = &Filter{}
var ExportConfig = &Export{}

type Import struct {
	Type   string
	Method string
	Path   string
}

type Export struct {
	Filter Filter
	Path   string
}

type Filter struct {
	Type      string
	Label     []string
	Condition map[string]string
}

func (i *Import) Parse() error {
	return nil
}

func (f *Filter) Parse() error {
	f.Condition = map[string]string{}
	if f.Type != "bastion" && f.Type != "host" {
		return errors.New("--type is only support one of [bastion, host]")
	}
	for _, label := range f.Label {
		match, _ := regexp.Match(".+=.+", []byte(label))
		if match {
			split := strings.Split(label, "=")
			f.Condition[split[0]] = split[1]
		}
	}
	return nil
}

func (e *Export) Parse() error {
	e.Filter.Condition = map[string]string{}
	if e.Filter.Type != "bastion" && e.Filter.Type != "host" && e.Filter.Type != "all" {
		return errors.New("--type is only support one of [bastion, host, all]")
	}
	for _, label := range e.Filter.Label {
		match, _ := regexp.Match(".+=.+", []byte(label))
		if match {
			split := strings.Split(label, "=")
			e.Filter.Condition[split[0]] = split[1]
		}
	}
	return nil
}
